// 订单管理相关 API
import request from '@/utils/request';

import { ApiResponse, PageResult } from '@/types/common';
import { 
  OrderInfo, 
  OrderForm,
  DemandOrder,
  DemandOrderForm,
  DemandOrderDetail,
  DemandOrderSearchParams,
  OrderSearchParams,
  OrderActionRequest,
  DemandOrderActionRequest,
  BatchOrderActionRequest,
  ModifyOrderAmountForm,
  UploadDataForm,
  OrderStatistics,
  MachineTimeRecord,
  OrderOperationRecord,
  SampleShipping
} from '@/types/order';

export const orderApi = {
  // ==================== 普通订单接口 ====================
  
  // 获取订单列表
  getOrders: (params: OrderSearchParams): Promise<ApiResponse<PageResult<OrderInfo>>> =>
    request.get('/orders', params as Record<string, unknown>),

  // 获取订单详情
  getOrder: (id: string): Promise<ApiResponse<OrderInfo>> =>
    request.get(`/orders/${id}`),

  // 创建订单
  createOrder: (data: OrderForm): Promise<ApiResponse<OrderInfo>> =>
    request.post('/orders', data),

  // 更新订单
  updateOrder: (id: string, data: Partial<OrderForm>): Promise<ApiResponse<OrderInfo>> =>
    request.put(`/orders/${id}`, data),

  // 删除订单
  deleteOrder: (id: string): Promise<ApiResponse<void>> =>
    request.delete(`/orders/${id}`),

  // 订单操作（通过、驳回、上机、下机等）
  orderAction: (data: OrderActionRequest): Promise<ApiResponse<void>> =>
    request.post(`/orders/${data.orderId}/action`, {
      action: data.action,
      remark: data.remark,
      data: data.data,
    }),

  // 批量订单操作
  batchOrderAction: (data: BatchOrderActionRequest): Promise<ApiResponse<void>> =>
    request.post('/orders/batch-action', data),

  // 修改订单金额
  updateOrderAmount: (data: ModifyOrderAmountForm): Promise<ApiResponse<void>> =>
    request.patch(`/orders/${data.orderId}/amount`, {
      newAmount: data.newAmount,
      remark: data.remark,
    }),

  // 上传实验数据
  uploadOrderData: async (data: UploadDataForm): Promise<ApiResponse<void>> => {
    const formData = new FormData();
    data.files.forEach(file => {
      formData.append('files', file);
    });
    if (data.description) {
      formData.append('description', data.description);
    }
    return request.upload(`/orders/${data.orderId}/upload-data`, formData);
  },

  // 下载实验数据
  downloadOrderData: async (orderId: string): Promise<Blob> => {
    const response = await fetch(`/api/orders/${orderId}/download-data`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${request.getToken()}`,
      },
    });
    return response.blob();
  },

  // 获取上下机记录
  getMachineTimeRecords: (orderId: string): Promise<ApiResponse<MachineTimeRecord[]>> =>
    request.get(`/orders/${orderId}/machine-time`),

  // 添加上下机记录
  addMachineTimeRecord: (orderId: string, type: 'on' | 'off'): Promise<ApiResponse<MachineTimeRecord>> =>
    request.post(`/orders/${orderId}/machine-time`, { type }),

  // 获取订单操作记录
  getOrderOperationRecords: (orderId: string): Promise<ApiResponse<OrderOperationRecord[]>> =>
    request.get(`/orders/${orderId}/operations`),

  // 获取样品邮寄信息
  getSampleShipping: (orderId: string): Promise<ApiResponse<SampleShipping>> =>
    request.get(`/orders/${orderId}/shipping`),

  // 更新样品邮寄信息
  updateSampleShipping: (orderId: string, data: Partial<SampleShipping>): Promise<ApiResponse<SampleShipping>> =>
    request.put(`/orders/${orderId}/shipping`, data),

  // ==================== 需求订单接口 ====================

  // 获取需求订单列表
  getDemandOrders: (params: DemandOrderSearchParams): Promise<ApiResponse<PageResult<DemandOrder>>> =>
    request.get('/demand-orders', params as Record<string, unknown>),

  // 获取需求订单详情
  getDemandOrder: (id: string): Promise<ApiResponse<DemandOrderDetail>> =>
    request.get(`/demand-orders/${id}`),

  // 创建需求订单
  createDemandOrder: (data: DemandOrderForm): Promise<ApiResponse<DemandOrder>> =>
    request.post('/demand-orders', data),

  // 更新需求订单
  updateDemandOrder: (id: string, data: Partial<DemandOrderForm>): Promise<ApiResponse<DemandOrder>> =>
    request.put(`/demand-orders/${id}`, data),

  // 删除需求订单
  deleteDemandOrder: (id: string): Promise<ApiResponse<void>> =>
    request.delete(`/demand-orders/${id}`),

  // 需求订单操作
  demandOrderAction: (data: DemandOrderActionRequest): Promise<ApiResponse<void>> =>
    request.post(`/demand-orders/${data.demandOrderId}/action`, {
      instrumentOrderId: data.instrumentOrderId,
      action: data.action,
      remark: data.remark,
      data: data.data,
    }),

  // 添加仪器到需求订单
  addInstrumentToDemandOrder: (demandOrderId: string, instrumentIds: string[]): Promise<ApiResponse<void>> =>
    request.post(`/demand-orders/${demandOrderId}/instruments`, { instrumentIds }),

  // 从需求订单移除仪器
  removeInstrumentFromDemandOrder: (demandOrderId: string, instrumentOrderId: string): Promise<ApiResponse<void>> =>
    request.delete(`/demand-orders/${demandOrderId}/instruments/${instrumentOrderId}`),

  // 更新需求订单中的仪器信息
  updateDemandOrderInstrument: (
    demandOrderId: string, 
    instrumentOrderId: string, 
    data: { notes?: string; amount?: number }
  ): Promise<ApiResponse<void>> =>
    request.patch(`/demand-orders/${demandOrderId}/instruments/${instrumentOrderId}`, data),

  // ==================== 统计接口 ====================

  // 获取订单统计信息
  getOrderStatistics: (params?: { 
    startDate?: string; 
    endDate?: string; 
    instrumentId?: string;
    userId?: string;
  }): Promise<ApiResponse<OrderStatistics>> =>
    request.get('/orders/statistics', params as Record<string, unknown>),

  // 获取需求订单统计信息
  getDemandOrderStatistics: (params?: {
    startDate?: string;
    endDate?: string;
    userId?: string;
  }): Promise<ApiResponse<OrderStatistics>> =>
    request.get('/demand-orders/statistics', params as Record<string, unknown>),

  // ==================== 导出接口 ====================

  // 导出订单列表
  exportOrders: async (params: OrderSearchParams): Promise<Blob> => {
    const queryString = new URLSearchParams(params as Record<string, string>).toString();
    const response = await fetch(`/api/orders/export?${queryString}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${request.getToken()}`,
      },
    });
    return response.blob();
  },

  // 导出需求订单列表
  exportDemandOrders: async (params: DemandOrderSearchParams): Promise<Blob> => {
    const queryString = new URLSearchParams(params as Record<string, string>).toString();
    const response = await fetch(`/api/demand-orders/export?${queryString}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${request.getToken()}`,
      },
    });
    return response.blob();
  },

  // ==================== 其他接口 ====================

  // 获取可选仪器列表（创建需求订单时使用）
  getAvailableInstruments: (params?: {
    category?: string;
    keyword?: string;
  }): Promise<ApiResponse<Array<{
    id: string;
    name: string;
    category: string;
    subcategory: string;
    price: number;
    unit: string;
    status: string;
  }>>> =>
    request.get('/instruments/available', params as Record<string, unknown>),

  // 检查余额/额度是否充足
  checkBalance: (params: {
    userId: string;
    amount: number;
    paymentMethod: string;
    teamId?: string;
  }): Promise<ApiResponse<{
    sufficient: boolean;
    currentBalance: number;
    required: number;
    message?: string;
  }>> =>
    request.post('/orders/check-balance', params),

  // 预估订单费用
  estimateOrderCost: (params: {
    instrumentId: string;
    orderType: string;
    duration?: number;
    consumables?: { id: string; quantity: number }[];
    services?: string[];
  }): Promise<ApiResponse<{
    total: number;
    breakdown: {
      instrumentCost: number;
      consumablesCost: number;
      servicesCost: number;
    };
  }>> =>
    request.post('/orders/estimate-cost', params),

  // 获取订单模板（预约申请单）
  getOrderTemplate: (instrumentId: string): Promise<ApiResponse<{
    id: string;
    instrumentId: string;
    templateContent: string;
    fields: Array<{
      name: string;
      type: string;
      label: string;
      required: boolean;
      options?: string[];
    }>;
  }>> =>
    request.get(`/instruments/${instrumentId}/order-template`),

  // 提交订单模板数据
  submitOrderTemplate: (orderId: string, templateData: Record<string, unknown>): Promise<ApiResponse<void>> =>
    request.post(`/orders/${orderId}/template-data`, { templateData }),
};
